﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace YueRu.Common
{
    /// <summary>
    /// 序列号帮助类
    /// </summary>
    public class SerializationHelper
    {
        /// <summary>
        /// 序列化，使用标准的XmlSerializer，优先考虑使用。
        /// 不能序列化IDictionary接口.
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static string Save(object obj, string filename)
        {
            FileStream fs = null;
            MemoryStream ms = null;
            try
            {
                //防止序列化出错更新到配置文件 所以先完成序列化 在保存
                var serializer = new XmlSerializer(obj.GetType());
                ms = new MemoryStream(13 * 1024); //初始缓冲区大小13k
                serializer.Serialize(ms, obj);

                var tmpContent = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());

                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                ms.WriteTo(fs);

                ms.Flush();
                fs.Flush();

                return tmpContent;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
            }

        }

        /// <summary>
        /// 反序列化，使用标准的XmlSerializer，优先考虑使用。
        /// 不能序列化IDictionary接口.
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filename">文件路径</param>
        /// <returns>type类型的对象实例</returns>
        public static object Load(Type type, string filename)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

        /// <summary>
        /// 反序列化类
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static T Load<T>(string filename) where T : class
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(fs) as T;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

    }
}